import pygame
from pygame.sprite import Sprite 
import os
from datetime import datetime
from collections import deque
from datetime import datetime
from .bullet import Bullet
from .eventCenter import EventCenter
from time import sleep

class Move:
    
    def __init__(self, rect):
        self.rect = rect
        self.speed = 4

    def up(self, speed=0):
        self.rect.centery -= speed or self.speed

    def down(self, speed=0):
        self.rect.centery += speed or self.speed
        
    def left(self, speed=0):
        self.rect.left -= speed or self.speed
        
    def right(self, speed=0):
        self.rect.right += speed or self.speed


class Air(Move, EventCenter):
    ''' 飞机类 '''

    def __init__(self, screen):
        
        self.screen = screen
        self.img = pygame.image.load('static/air-mini.png')
        self.rect = self.img.get_rect()
        self.screen_rect = screen.get_rect()

        self.rect.centery = self.screen_rect.centery
        self.rect.left = self.screen_rect.left + 20
        self.moveStore = []
        self.createTime = datetime.now()
        self.action = {
            pygame.K_UP: self.up,
            pygame.K_DOWN: self.down,
            pygame.K_LEFT: self.left,
            pygame.K_RIGHT: self.right,
            pygame.K_f: self.shoot
        }

        self.eventMap = {
            pygame.KEYDOWN: self.onKeyDown,
            pygame.KEYUP: self.onKeyUp,
        }

        self.bindEvent()
        super().__init__(self.rect)
        
        
    def shoot(self):
        ''' 触发shoot事件 '''

        self.trigger('shoot', {
            "x": self.rect.centerx,
            "y": self.rect.centery
        })
        

    def blitme(self, event):
        ''' 创建飞机 '''
        self.screen.blit(self.img, self.rect)

    def onKeyDown(self, event):
        if event.key in self.action.keys():
            self.moveStore.append(event.key)
        
    def onKeyUp(self, event):
         if event.key in self.moveStore:
            self.moveStore.remove(event.key)


    def bindEvent(self):
        for key, fn in self.eventMap.items():
            self.registered(key, fn)


    def update(self, event):
        
        for key in self.moveStore:
            self.action[key]()
        
    def removeEvent(self):
        for eventName, fn in self.eventMap.items():
            self.remove(eventName)
   
        
    
    
                